﻿using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace Fluffy.Library.Behaviors
{
	public class CloseWindowBehavior : Behavior<Window>
    {
		public static readonly DependencyProperty CommandProperty = DependencyProperty.Register(
			"Command", typeof (ICommand), typeof (CloseWindowBehavior), new PropertyMetadata(null));

		public ICommand Command
		{
			get { return (ICommand) GetValue(CommandProperty); }
			set { SetValue(CommandProperty, value); }
		}

        protected override void OnAttached()
        {
            base.OnAttached();

            AssociatedObject.Closing += OnWindowClose;
        }

		protected override void OnDetaching()
		{
			base.OnDetaching();

			AssociatedObject.Closing -= OnWindowClose;
		}

		private void OnWindowClose(object sender, EventArgs e)
		{
			if (Command != null)
				Command.Execute(null);
		}
    }
}
